package com.virtualperson.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.virtualperson.config.AliyunConfig;
import com.virtualperson.service.ObjectStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
public class AliyunOssStorageServiceImpl implements ObjectStorageService {

    @Autowired
    private AliyunConfig aliyunConfig;

    @Override
    public String uploadFile(File file) {
        String endpoint = aliyunConfig.getOssEndpoint();
        String accessKeyId = aliyunConfig.getAccessKeyId();
        String accessKeySecret = aliyunConfig.getAccessKeySecret();
        String bucketName = aliyunConfig.getBucketName();

        if (endpoint == null || endpoint.trim().isEmpty()) {
            throw new RuntimeException("阿里云OSS endpoint未配置");
        }
        if (accessKeyId == null || accessKeyId.trim().isEmpty()) {
            throw new RuntimeException("阿里云AccessKeyId未配置");
        }
        if (accessKeySecret == null || accessKeySecret.trim().isEmpty()) {
            throw new RuntimeException("阿里云AccessKeySecret未配置");
        }
        if (bucketName == null || bucketName.trim().isEmpty()) {
            throw new RuntimeException("阿里云OSS Bucket名称未配置");
        }

        OSS ossClient = null;
        try {
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 生成对象键（文件路径）
            String objectKey = generateObjectKey(file.getName());

            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectKey, file);

            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("文件上传成功: bucket={}, objectKey={}, etag={}", bucketName, objectKey, result.getETag());

            // 返回文件访问URL
            return generateFileUrl(bucketName, objectKey, endpoint);

        } catch (Exception e) {
            log.error("文件上传失败: {}", file.getAbsolutePath(), e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void deleteFile(String fileUrl) {
        String endpoint = aliyunConfig.getOssEndpoint();
        String accessKeyId = aliyunConfig.getAccessKeyId();
        String accessKeySecret = aliyunConfig.getAccessKeySecret();
        String bucketName = aliyunConfig.getBucketName();

        OSS ossClient = null;
        try {
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 从URL中提取对象键
            String objectKey = extractObjectKeyFromUrl(fileUrl, bucketName, endpoint);

            // 删除文件
            ossClient.deleteObject(bucketName, objectKey);
            log.info("文件删除成功: bucket={}, objectKey={}", bucketName, objectKey);

        } catch (Exception e) {
            log.error("文件删除失败: {}", fileUrl, e);
            throw new RuntimeException("文件删除失败: " + e.getMessage());
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public String getFileUrl(String fileKey) {
        String endpoint = aliyunConfig.getOssEndpoint();
        String bucketName = aliyunConfig.getBucketName();
        return generateFileUrl(bucketName, fileKey, endpoint);
    }

    /**
     * 生成对象键（文件路径）
     */
    private String generateObjectKey(String originalFileName) {
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String timeStr = now.format(DateTimeFormatter.ofPattern("HHmmss"));
        String uuid = UUID.randomUUID().toString().substring(0, 8);
        
        // 获取文件扩展名
        String extension = "";
        if (originalFileName.contains(".")) {
            extension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        }
        
        return String.format("uploads/%s/%s_%s%s", dateStr, timeStr, uuid, extension);
    }

    /**
     * 生成文件访问URL
     */
    private String generateFileUrl(String bucketName, String objectKey, String endpoint) {
        // 根据endpoint判断是否使用HTTPS
        String protocol = endpoint.startsWith("https") ? "https" : "http";
        String host = endpoint.replace("https://", "").replace("http://", "");
        
        return String.format("%s://%s.%s/%s", protocol, bucketName, host, objectKey);
    }

    /**
     * 从URL中提取对象键
     */
    private String extractObjectKeyFromUrl(String fileUrl, String bucketName, String endpoint) {
        String host = endpoint.replace("https://", "").replace("http://", "");
        String prefix = String.format("%s.%s/", bucketName, host);
        
        if (fileUrl.contains(prefix)) {
            return fileUrl.substring(fileUrl.indexOf(prefix) + prefix.length());
        }
        
        throw new IllegalArgumentException("无法从URL中提取对象键: " + fileUrl);
    }
} 